package cn.darkfire.web.Controller;

import cn.darkfire.web.POJO.LoginUser;
import cn.darkfire.web.POJO.Status;
import cn.darkfire.web.Service.UserService;
import cn.darkfire.web.Service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "syLogin")
public class Sy4LoginController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("name");
        String password = req.getParameter("password");
        String isSave = req.getParameter("isSave");
        String code = (String)req.getSession().getAttribute("code");
        String code_user = req.getParameter("code");
        if(code==null||!code.equals(code_user)){
            req.getSession().setAttribute("error","登录失败！验证码错误！");
            resp.sendRedirect("./login.jsp");
            return;
        }
        UserService userService = new UserServiceImpl();
        Status status = userService.login(new LoginUser(username,password));
        if(status.getCode()==200){
            //登录成功
            if(isSave!=null){
                if(isSave.equals("1")){
                    Cookie p_cookie = new Cookie("password",password);
                    Cookie u_cookie = new Cookie("username",username);
                    resp.addCookie(p_cookie);
                    resp.addCookie(u_cookie);
                }else{
                    Cookie p_cookie = new Cookie("password","");
                    Cookie u_cookie = new Cookie("username","");
                    p_cookie.setMaxAge(0);
                    u_cookie.setMaxAge(0);
                    resp.addCookie(p_cookie);
                    resp.addCookie(u_cookie);
                }
            }else{
                Cookie p_cookie = new Cookie("password","");
                Cookie u_cookie = new Cookie("username","");
                p_cookie.setMaxAge(0);
                u_cookie.setMaxAge(0);
                resp.addCookie(p_cookie);
                resp.addCookie(u_cookie);
            }
//            req.getSession().setAttribute("users",userService.getAllUser());
            req.getSession().setAttribute("user",username);
//            resp.sendRedirect("./index.jsp");
            resp.sendRedirect("./getUserByPage.do?page=1&num=10");

        }else{
            req.getSession().setAttribute("error","登录失败！账号密码错误或账户不存在！");
            resp.sendRedirect("./login.jsp");
        }
    }
}
